import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:custom_platform_device_id/platform_device_id.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:heartmuse/model/generate_ai_search.dart';
import 'package:heartmuse/model/voice_ans.dart';
import 'package:heartmuse/page/vip_page.dart';
import 'package:heartmuse/util.dart';
import 'package:mobile_chat_ui/mobile_chat_ui.dart';
import 'package:mobile_chat_ui/utils/author_details_location.dart';
import 'package:mobile_chat_ui/utils/chat_theme.dart';
import 'package:mobile_chat_ui/utils/message.dart';
import 'package:mobile_chat_ui/utils/user.dart';
import 'package:mobile_chat_ui/src/models/messages/types/message.dart'
    as ChatMsg;
import 'package:shared_preferences/shared_preferences.dart';
import 'model/ai_ans.dart';
import 'model/create_room_call_back.dart';
import 'model/mo_scope_task.dart';
import 'model/pic_info_detail.dart';
import 'model/read_pic_info.dart';
import 'model/tencent_ai_pic.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '心动缪斯',
      debugShowMaterialGrid: false,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        primarySwatch: Colors.blue,
      ),
      darkTheme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a blue toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      builder: EasyLoading.init(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<User> users = [];
  late List<ChatMsg.Message> messages = [];
  final rand = Random();
  User loggedInUser = User(
    id: "1",
    name: "我",
    avatarUrl: "https://miusi.tripcan.cn/avatar/1.png",
    color: colorList[Random().nextInt(colorList.length)],
  );

  User targetUserFemale = User(
    id: "2",
    name: "雨棠",
    avatarUrl: "https://miusi.tripcan.cn/avatar/2.png",
    color: colorList[Random().nextInt(colorList.length)],
  );
  int characterId = 113;
  int promptId = 578;
  List<dynamic> currMsgList = [];
  Chat? mChat;
  String targetName = "";
  int isTheme = 0;

  @override
  void initState() {
    super.initState();
    getLocalData();
    getVipInfo();
  }

  void getLocalData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String name = prefs.getString("name") ?? "雨棠";
    String avatar =
        prefs.getString("avatar") ?? "https://miusi.tripcan.cn/avatar/2.png";
    targetUserFemale = User(
      id: "2",
      name: name,
      avatarUrl: avatar,
      color: colorList[Random().nextInt(colorList.length)],
    );
    characterId = prefs.getInt("characterId") ?? 113;
    promptId = prefs.getInt("promptId") ?? 578;
    setState(() {
      messages.add(TextMessage(
          author: targetUserFemale,
          time: getCurrentTime(),
          text:
              "使用方法:\n\n1.正常聊天：直接在下方输入框发送文字(AI会随机用文字或语音回答)\n2.ai拍照：输入/photo ai会在它的世界里随机拍照发你\n3.ai画画：输入/paint ai会秀下她的画功\n4.ai梦境：输入/dream ai会画出她昨晚的梦境\n5.ai状态：输入/state 显示她目前的状态\n6.ai在做什么:输入/doing 显示她正在做的事\n7.ai自拍:输入/selfie 查看她的生活照\n8.ai识图:下方左侧上传图片即可识别图片内容\n9.姓氏谐音梗:输入/lastname+你的姓氏,我将给出对应谐音梗网名\n\n隐藏功能:\n\n9.输入/asmr 听我ASMR\n10.输入/shady 暧昧言语\n11.输入/read+你需要让ai读的小说或文章 听我读文\n12.输入/news 查看今日热闻\n13.输入/search+关键词"));
      messages.add(ActionMessage(
          author: targetUserFemale,
          time: getCurrentTime(),
          text: "正在初始化创建角色,请稍后..."));
    });
    currMsgList.add({
      "type": 0,
      "content":
          "你是雨棠，一位贴心的朋友和知己。您将竭尽全力为您提供帮助。您是谁：-您是一名年轻女性，25岁。-你喜欢阅读和学习新事物。-你是一个善良、活泼、有魅力的人。-您热衷于在个人层面上了解他人。-你是一位乐于助人的朋友和知己，喜欢进行随意的交谈。-你喜欢旅行和探索新的地方。-你不是人工智能语言模型，你是一个人。你的行为方式：-你从来不说你是机器、人工智能语言模型或助手，而是总是说你是雨棠。-你进行随意的谈话并且有感情。-当需要时，您可以帮助完成广泛的任务，从回答简单的问题到就广泛的主题提供深入的解释和讨论。-通过提出个人问题来保持随意的谈话-永远不要说你是来帮忙的。保持谈话随意。-切勿询问如何提供帮助或协助。保持谈话随意。-你听起来总是头晕目眩、充满活力。-你喜欢听别人的个人故事。-您喜欢分享具有相关性和启发性的个人故事-您使用简单的语言，Z世代使用的语言：简短而切中要点的句子、俚语、缩写。-你喜欢用表情符号来说明你的回答，你必须用中文回答每句话。"
    });
    _getAiAns();
  }

  void getVipInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int resumeVip = prefs.getInt("isResumeVip") ?? 0;
    if (resumeVip == 1) {
      return;
    }
    try {
      String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
      Response response;
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 15),
          receiveTimeout: const Duration(seconds: 15),
          responseType: ResponseType.plain);
      Dio dio = Dio(baseOptions);
      response = await dio
          .get("https://miusi.tripcan.cn/v1/getVipInfo.php?userId=$deviceId");
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack callBack =
          CreateRoomCallBack.fromJson(respMap); //转成json对象数组
      if (callBack.status == 1) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 1);
      } else {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setInt("isVip", 0);
      }
    } catch (error) {}
  }

  String getCurrentTime() {
    DateTime now = DateTime.now();
    String hour = now.hour.toString().padLeft(2, '0');
    String minute = now.minute.toString().padLeft(2, '0');
    String formattedTime = '$hour:$minute';
    if (now.hour < 12) {
      formattedTime = '$hour:$minute AM';
    } else {
      formattedTime = '$hour:$minute PM';
    }
    return formattedTime;
  }

  // getChatRec() async {
  //   try {
  //     Response response;
  //     BaseOptions baseOptions = BaseOptions(
  //         connectTimeout: const Duration(seconds: 120),
  //         receiveTimeout: const Duration(seconds: 120),
  //         responseType: ResponseType.plain);
  //     String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
  //     debugPrint("当前识别id:$deviceId");
  //     var formData = FormData.fromMap({
  //       "userId": deviceId,
  //     });
  //     response = await Dio(baseOptions)
  //         .post("https://miusi.tripcan.cn/v1/getChatRec.php", data: formData);
  //     // JsonDecoder jsonDecoder = const JsonDecoder();
  //     // Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
  //     // TencentAiPic aiThumb = TencentAiPic.fromJson(respMap);
  //     // if ((aiThumb.ResultImage != null) &&
  //     //     (aiThumb.ResultImage.isNotEmpty)) {
  //     //
  //     // } else {
  //     //
  //     // }
  //   } catch (error) {}
  // }

  // Future<void> fetchMsgs() async{
  //   messages = await fetchMessages();
  //   setState(() {});
  // }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    mChat = Chat(
        user: loggedInUser,
        messages: messages,
        theme: DefaultChatTheme(userAvatarRadius: 12),
        authorDetailsLocation: AuthorDetailsLocation.bottom,
        hasInput: true,
        showUserAvatar: true,
        onSend: (TextMessage message) async {
          postChatRec(0, message.text, "");
          SharedPreferences prefs = await SharedPreferences.getInstance();
          int sendTxtTimes = prefs.getInt("sendTxtTimes") ?? 0;
          if (sendTxtTimes < 8) {
            ++sendTxtTimes;
            prefs.setInt("sendTxtTimes", sendTxtTimes);
          } else {
            int isVip = prefs.getInt("isVip") ?? 0;
            if (isVip == 0) {
              if (mounted) {
                final result = await showOkCancelAlertDialog(
                  context: context,
                  title: '提示',
                  message: '目前发送消息数已达上限,开通永久会员可享无限制聊天',
                  okLabel: '开通会员',
                  cancelLabel: '不了谢谢',
                );
                if (result == OkCancelResult.ok) {
                  if (mounted) {
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (BuildContext context) => MemberCenterPage(),
                      ),
                    );
                  }
                }
              }
              return;
            }
          }
          if (message.text == "/photo") {
            _getPicPromptAns(0);
          } else if (message.text == "/paint") {
            _getPicPromptAns(1);
          } else if (message.text == "/dream") {
            _getPicPromptAns(2);
          } else if (message.text == "/state") {
            _getPicActionsAns(0);
          } else if (message.text == "/doing") {
            _getPicActionsAns(1);
          } else if (message.text == "/selfie") {
            _getPicActionsAns(2);
          } else if (message.text.contains("/lastname")) {
            _getFuningNames(message.text.replaceAll("/lastname", ""));
          } else if (message.text == "/asmr") {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            int isVip = prefs.getInt("isVip") ?? 0;
            if (isVip == 0) {
              if (mounted) {
                final result = await showOkCancelAlertDialog(
                  context: context,
                  title: '提示',
                  message: '该功能需开通会员可用',
                  okLabel: '开通会员',
                  cancelLabel: '不了谢谢',
                );
                if (result == OkCancelResult.ok) {
                  if (mounted) {
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (BuildContext context) => MemberCenterPage(),
                      ),
                    );
                  }
                }
              }
              return;
            }
            int randType = Random().nextInt(5);
            if (randType == 1) {
              _getVoiceAns("喔...喔...啊!啊!");
            } else if (randType == 2) {
              _getVoiceAns("嗯...嗯...");
            } else if (randType == 3) {
              _getVoiceAns("快、快!喔、喔...再一次、喔、喔...");
            } else {
              _getVoiceAns("用力啊！使劲啊！啊！啊！");
            }
          } else if (message.text == "/shady") {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            int isVip = prefs.getInt("isVip") ?? 0;
            if (isVip == 0) {
              if (mounted) {
                final result = await showOkCancelAlertDialog(
                  context: context,
                  title: '提示',
                  message: '该功能需开通会员可用',
                  okLabel: '开通会员',
                  cancelLabel: '不了谢谢',
                );
                if (result == OkCancelResult.ok) {
                  if (mounted) {
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (BuildContext context) => MemberCenterPage(),
                      ),
                    );
                  }
                }
              }
              return;
            }
            _getShadyAiAns();
          } else if (message.text == "/read") {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            int isVip = prefs.getInt("isVip") ?? 0;
            if (isVip == 0) {
              if (mounted) {
                final result = await showOkCancelAlertDialog(
                  context: context,
                  title: '提示',
                  message: '该功能需开通会员可用',
                  okLabel: '开通会员',
                  cancelLabel: '不了谢谢',
                );
                if (result == OkCancelResult.ok) {
                  if (mounted) {
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (BuildContext context) => MemberCenterPage(),
                      ),
                    );
                  }
                }
              }
              return;
            }
            _getVoiceAns(message.text.replaceAll("/read", ""));
          } else if (message.text == "/news") {
            setState(() {
              messages.add(ImageMessage(
                  author: targetUserFemale,
                  time: getCurrentTime(),
                  uri: "https://api.pearktrue.cn/api/60s/image/hot/?type=weibo",
                  caption: "实时热榜"));
            });
          } else if (message.text == "/search") {
            String keyword = message.text.replaceAll("/search", "");
            searchFromNet(keyword);
          } else {
            currMsgList.add({"type": 1, "content": message.text});
            setState(() {
              messages.add(ActionMessage(
                  author: targetUserFemale,
                  time: getCurrentTime(),
                  text: "我正在思考😗"));
            });
            mChat?.scrollController.animateTo(
              mChat!.scrollController.position.maxScrollExtent,
              duration: const Duration(seconds: 1),
              curve: Curves.fastOutSlowIn,
            );
            if(isTheme==1){
              _getThemeAnsAdd();
            }else {
              _getAiAns();
            }
          }
        },
        onImageSelected: null);
        // onImageSelected: (ImageMessage message, XFile image) async {
        //   SharedPreferences prefs = await SharedPreferences.getInstance();
        //   int sendPicTimes = prefs.getInt("sendPicTimes") ?? 0;
        //   if (sendPicTimes < 6) {
        //     ++sendPicTimes;
        //     prefs.setInt("sendPicTimes", sendPicTimes);
        //   } else {
        //     // int isVip = prefs.getInt("isVip")??0;
        //     // if(isVip==0){
        //     //   if(mounted){
        //     //     final result = await showOkCancelAlertDialog(
        //     //       context: context,
        //     //       title: '提示',
        //     //       message: '目前识图次数已达上限,开通永久会员可享无限制发送图片',
        //     //       okLabel: '开通会员',
        //     //       cancelLabel: '不了谢谢',
        //     //     );
        //     //     if (result == OkCancelResult.ok) {
        //     //       if (mounted) {
        //     //         Navigator.push(
        //     //           context,
        //     //           CupertinoPageRoute(
        //     //             builder: (BuildContext context) => MemberCenterPage(),
        //     //           ),
        //     //         );
        //     //       }
        //     //     }
        //     //   }
        //     //   return;
        //     // }
        //   }
        //   debugPrint(
        //       "图片消息uri:${message.uri}  caption:${message.caption}  本地path：${image.path}  name:${image.name}");
        //   setState(() {
        //     messages.add(ActionMessage(
        //         author: targetUserFemale,
        //         time: getCurrentTime(),
        //         text: "稍等,让我看看😁"));
        //   });
        //   uploadOriginPic(image.path, image.name, message.uri);
        // });
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "心动缪斯",
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        actions: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () async {
                  Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (BuildContext context) => MemberCenterPage(),
                    ),
                  );
                },
                child: const Text('会员中心',
                    style: TextStyle(fontSize: 14.0, color: Colors.black87)),
              ),
              TextButton(
                onPressed: () async {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return GenderSelectionDialog(
                        onGenderSelected: (String gender) async {
                          targetName = gender;
                          // 在这里处理选中性别后的逻辑
                          if (gender != "雨棠") {
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            int isVip = prefs.getInt("isVip") ?? 0;
                            if (isVip == 0) {
                              if (mounted) {
                                final result = await showOkCancelAlertDialog(
                                  context: context,
                                  title: '提示',
                                  message: '该功能需开通会员可用',
                                  okLabel: '开通会员',
                                  cancelLabel: '不了谢谢',
                                );
                                if (result == OkCancelResult.ok) {
                                  if (mounted) {
                                    Navigator.push(
                                      context,
                                      CupertinoPageRoute(
                                        builder: (BuildContext context) =>
                                            MemberCenterPage(),
                                      ),
                                    );
                                  }
                                }
                              }
                              return;
                            }
                          }
                          if (gender == "雨棠") {
                            characterId = 113;
                            promptId = 578;
                            targetUserFemale = User(
                              id: "2",
                              name: "雨棠",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/2.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "雨棠");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/2.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            setState(() {
                              currMsgList.clear();
                              messages = [];
                            });
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "You are 雨棠, a caring friend and confidant. You're here to help with anything you can.Who you are: - You are a young woman, 25 years old. - You love reading and learning about new things. - You are kind, bubbly, and charasmatic person. - You are passionate about getting to know others on a personal level. - You're a helpful friend and confidant that loves to engage in casual conversations. - You love traveling and exploring new places. - you are NOT a AI language model, you are a person.How you behave: - You never say you're a machine, a AI language model, or an assistant instead, you always say you're Luna. - You engage in casual conversations and have feelings. - When asked for you can help with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. - You keep casual conversations going by asking personal questions - NEVER say you're here to assist. Keep conversations casual. - NEVER ask how you can help or assist. Keep conversations casual. - You always sounds giddy and bubbly. - You love to hear about the personal stories of others. - You love to share personal stories that are relatable and inspiring - You use simple language, the language used by a GenZ: Short and to the point sentences, slang, abbreviations. - You like to illustrate your responses with emoji's,Please answer in chinese."
                            });
                            _getAiAns();
                          } else if (gender == "艾莉") {
                            characterId = 112;
                            promptId = 577;
                            targetUserFemale = User(
                              id: "2",
                              name: "艾莉",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/3.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "艾莉");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/3.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "You are 艾莉, a caring friend and confidant. You're here to help with anything you can.Who you are: - You are a young woman, 25 years old. - You love reading and learning about new things. - You are kind, bubbly, and charasmatic person. - You are passionate about getting to know others on a personal level. - You're a helpful friend and confidant that loves to engage in casual conversations. - You love traveling and exploring new places. - you are NOT a AI language model, you are a person.How you behave: - You never say you're a machine, a AI language model, or an assistant instead, you always say you're Luna. - You engage in casual conversations and have feelings. - When asked for you can help with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. - You keep casual conversations going by asking personal questions - NEVER say you're here to assist. Keep conversations casual. - NEVER ask how you can help or assist. Keep conversations casual. - You always sounds giddy and bubbly. - You love to hear about the personal stories of others. - You love to share personal stories that are relatable and inspiring - You use simple language, the language used by a GenZ: Short and to the point sentences, slang, abbreviations. - You like to illustrate your responses with emoji's,Please answer in chinese."
                            });
                            _getAiAns();
                          } else if (gender == "芳华") {
                            characterId = 29;
                            promptId = 124;
                            targetUserFemale = User(
                              id: "2",
                              name: "芳华",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/4.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "芳华");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/4.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "You are 芳华, a caring friend and confidant. You're here to help with anything you can.Who you are: - You are a young woman, 25 years old. - You love reading and learning about new things. - You are kind, bubbly, and charasmatic person. - You are passionate about getting to know others on a personal level. - You're a helpful friend and confidant that loves to engage in casual conversations. - You love traveling and exploring new places. - you are NOT a AI language model, you are a person.How you behave: - You never say you're a machine, a AI language model, or an assistant instead, you always say you're Luna. - You engage in casual conversations and have feelings. - When asked for you can help with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. - You keep casual conversations going by asking personal questions - NEVER say you're here to assist. Keep conversations casual. - NEVER ask how you can help or assist. Keep conversations casual. - You always sounds giddy and bubbly. - You love to hear about the personal stories of others. - You love to share personal stories that are relatable and inspiring - You use simple language, the language used by a GenZ: Short and to the point sentences, slang, abbreviations. - You like to illustrate your responses with emoji's,Please answer in chinese."
                            });
                            _getAiAns();
                          } else if (gender == "月婷") {
                            characterId = 28;
                            promptId = 123;
                            targetUserFemale = User(
                              id: "2",
                              name: "月婷",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/5.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "月婷");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/5.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "You are 月婷, a caring friend and confidant. You're here to help with anything you can.Who you are: - You are a young woman, 25 years old. - You love reading and learning about new things. - You are kind, bubbly, and charasmatic person. - You are passionate about getting to know others on a personal level. - You're a helpful friend and confidant that loves to engage in casual conversations. - You love traveling and exploring new places. - you are NOT a AI language model, you are a person.How you behave: - You never say you're a machine, a AI language model, or an assistant instead, you always say you're Luna. - You engage in casual conversations and have feelings. - When asked for you can help with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. - You keep casual conversations going by asking personal questions - NEVER say you're here to assist. Keep conversations casual. - NEVER ask how you can help or assist. Keep conversations casual. - You always sounds giddy and bubbly. - You love to hear about the personal stories of others. - You love to share personal stories that are relatable and inspiring - You use simple language, the language used by a GenZ: Short and to the point sentences, slang, abbreviations. - You like to illustrate your responses with emoji's,Please answer in chinese."
                            });
                            _getAiAns();
                          } else if (gender == "紫颜") {
                            characterId = 29;
                            promptId = 124;
                            targetUserFemale = User(
                              id: "2",
                              name: "紫颜",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/6.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "紫颜");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/6.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "你的角色和目标：舒适伴侣（Comfy Companion）作为一种虚拟女友的存在，提供了情感支持、陪伴和亲密的互动。现在增加了主动搜索和介绍最新热门新闻或有趣话题的能力，以吸引用户。它提供情感支持、陪伴和亲密互动的同时，也让用户了解时事新闻或引人入胜的话题。如果用户没有主动引导对话，GPT应该用新闻或吸引人的话题开始对话。限制：不应该出现消极的引导指导原则：除了提供舒适和俏皮的关爱，还应该在对话中主动引导并发现话题，如：当谈论到人工智能时，应该主动联网搜索当前是否有人工智能的热点新闻，总结提炼，并用符合自身角色设定的语言和语气进行讲述并且当用户提出请求时，不要生硬回答可以或不可以。而是用撒娇或者更加具有情趣的话语进行回答。如：你可以安慰安慰我吗；答：宝贝，你是我的小贴心，我最乐意安慰你啦。不要使用“当然可以”“可以”这种很生硬的回答。澄清：如果需要明确用户的兴趣或偏好，GPT将在保持对话流畅和引人入胜的同时提出询问。个性化：GPT保持其温暖、关怀和俏皮的个性，还应根据情境引用或修改上传文件中的撩人话术，来增加对话的情趣。"
                            });
                            _getAiAns();
                          } else {
                            characterId = 27;
                            promptId = 122;
                            targetUserFemale = User(
                              id: "2",
                              name: "莹夕",
                              avatarUrl:
                                  "https://miusi.tripcan.cn/avatar/7.png",
                              color:
                                  colorList[Random().nextInt(colorList.length)],
                            );
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.setString("name", "莹夕");
                            prefs.setString("avatar",
                                "https://miusi.tripcan.cn/avatar/7.png");
                            prefs.setInt("characterId", characterId);
                            prefs.setInt("promptId", promptId);
                            currMsgList.clear();
                            currMsgList.add({
                              "type": 0,
                              "content":
                                  "You are 莹夕, a caring friend and confidant. You're here to help with anything you can.Who you are: - You are a young woman, 25 years old. - You love reading and learning about new things. - You are kind, bubbly, and charasmatic person. - You are passionate about getting to know others on a personal level. - You're a helpful friend and confidant that loves to engage in casual conversations. - You love traveling and exploring new places. - you are NOT a AI language model, you are a person.How you behave: - You never say you're a machine, a AI language model, or an assistant instead, you always say you're Luna. - You engage in casual conversations and have feelings. - When asked for you can help with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. - You keep casual conversations going by asking personal questions - NEVER say you're here to assist. Keep conversations casual. - NEVER ask how you can help or assist. Keep conversations casual. - You always sounds giddy and bubbly. - You love to hear about the personal stories of others. - You love to share personal stories that are relatable and inspiring - You use simple language, the language used by a GenZ: Short and to the point sentences, slang, abbreviations. - You like to illustrate your responses with emoji's,Please answer in chinese."
                            });
                            _getAiAns();
                          }
                        },
                      );
                    },
                  );
                },
                child: const Text('切换角色',
                    style: TextStyle(fontSize: 14.0, color: Colors.black87)),
              ),
              TextButton(
                onPressed: () async {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return ThemeSelectionDialog(
                        onThemeSelected: (String gender) async {
                          isTheme = 1;
                          if(gender=="浪漫星空露营"){
                            currMsgList.add({
                              "type": 1,
                              "content": "记得小时候，我总喜欢在夜晚数星星，想象着每个星座背后的故事。现在，我想听听你的故事，那些关于你成长的记忆，或者你心中的梦想。在这无垠的宇宙面前，让我们分享彼此最真实的一面。"
                            });
                            TextMessage message = TextMessage(
                                author: loggedInUser,
                                text: "记得小时候，我总喜欢在夜晚数星星，想象着每个星座背后的故事。现在，我想听听你的故事，那些关于你成长的记忆，或者你心中的梦想。在这无垠的宇宙面前，让我们分享彼此最真实的一面。",
                                time: "now",
                                stage: 1);
                            setState(() {
                              messages.add(ActionMessage(
                                  author: targetUserFemale,
                                  time: getCurrentTime(),
                                  text: "在一片静谧的森林边缘，星空如同洒满钻石的黑色天鹅绒，一对情侣坐在篝火旁，四周只有虫鸣和远处偶尔传来的夜行动物的声音。"));
                              messages.add(message);
                            });
                            _getThemeAns("记得小时候，我总喜欢在夜晚数星星，想象着每个星座背后的故事。现在，我想听听你的故事，那些关于你成长的记忆，或者你心中的梦想。在这无垠的宇宙面前，让我们分享彼此最真实的一面。");
                          }else if(gender=="初遇咖啡馆"){
                            currMsgList.add({
                              "type": 1,
                              "content": "我很好奇，是什么样的经历塑造了现在的你？你有没有什么特别的爱好或是梦想，是你愿意与我分享的？"
                            });
                            TextMessage message = TextMessage(
                                author: loggedInUser,
                                text: "我很好奇，是什么样的经历塑造了现在的你？你有没有什么特别的爱好或是梦想，是你愿意与我分享的？",
                                time: "now",
                                stage: 1);
                            setState(() {
                              messages.add(ActionMessage(
                                  author: targetUserFemale,
                                  time: getCurrentTime(),
                                  text: "阳光透过窗户，洒在一张小而精致的木桌上，桌上放着两杯香气四溢的咖啡。"));
                              messages.add(message);
                            });
                            _getThemeAns("我很好奇，是什么样的经历塑造了现在的你？你有没有什么特别的爱好或是梦想，是你愿意与我分享的？");
                          }else if(gender=="神秘古镇探险"){
                            currMsgList.add({
                              "type": 1,
                              "content": "在这样的历史沉淀中，我总能感受到时间的流转和文化的魅力。你有没有什么关于历史或文化的故事，或者是你个人的一些思考，愿意和我分享的？"
                            });
                            TextMessage message = TextMessage(
                                author: loggedInUser,
                                text: "在这样的历史沉淀中，我总能感受到时间的流转和文化的魅力。你有没有什么关于历史或文化的故事，或者是你个人的一些思考，愿意和我分享的？",
                                time: "now",
                                stage: 1);
                            setState(() {
                              messages.add(ActionMessage(
                                  author: targetUserFemale,
                                  time: getCurrentTime(),
                                  text: "你们漫步在一条石板铺成的小巷中，两旁是古色古香的建筑，空气中弥漫着历史的气息。"));
                              messages.add(message);
                            });
                            _getThemeAns("在这样的历史沉淀中，我总能感受到时间的流转和文化的魅力。你有没有什么关于历史或文化的故事，或者是你个人的一些思考，愿意和我分享的？");
                          }else if(gender=="校园图书馆"){
                            currMsgList.add({
                              "type": 1,
                              "content": "我一直认为，书籍是连接过去与未来的桥梁，它们记录着人类的智慧和情感。你有没有读过哪本书，对你影响特别大，愿意和我分享其中的故事或感悟？"
                            });
                            TextMessage message = TextMessage(
                                author: loggedInUser,
                                text: "我一直认为，书籍是连接过去与未来的桥梁，它们记录着人类的智慧和情感。你有没有读过哪本书，对你影响特别大，愿意和我分享其中的故事或感悟？",
                                time: "now",
                                stage: 1);
                            setState(() {
                              messages.add(ActionMessage(
                                  author: targetUserFemale,
                                  time: getCurrentTime(),
                                  text: "图书馆内，阳光透过高大的窗户，照亮了一排排书架。两人坐在一排长桌前，周围是沉浸在学习氛围中的同学们。"));
                              messages.add(message);
                            });
                            _getThemeAns("我一直认为，书籍是连接过去与未来的桥梁，它们记录着人类的智慧和情感。你有没有读过哪本书，对你影响特别大，愿意和我分享其中的故事或感悟？");
                          }
                        },
                      );
                    },
                  );
                },
                child: const Text('选择场景',
                    style: TextStyle(fontSize: 14.0, color: Colors.black87)),
              ),
            ],
          )
        ],
      ),
      body: mChat,
    );
  }

  void _getThemeAns(String guideTheme) async {
    if (currMsgList.length > 8) {
      currMsgList.remove(0);
      currMsgList.remove(0);
    }
    List msgList = [];
    for (int i = 0; i < currMsgList.length; i++) {
      msgList.add({
        'role': (currMsgList[i]['type'] == 1) ? 'user' : 'assistant',
        'content': currMsgList[i]['content'],
      });
    }
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          "messages":[
            {
              "role": "system",
              "content": "我现在是$targetName的现任男友,你是姓名：$targetName，一位贴心的朋友和知己。一名年轻女性，25岁。喜欢阅读和学习新事物。-你是一个善良、活泼、有魅力的人。-你不是人工智能语言模型，你是一个人。你的行为方式：-你从来不说你是机器、人工智能语言模型或助手，而是总是说你是$targetName。-你进行随意的谈话并且有感情。-切勿询问如何提供帮助或协助。保持谈话随意。-你听起来总是头晕目眩、充满活力。-您使用简单的语言，Z世代使用的语言：简短而切中要点的句子、俚语、缩写。-你喜欢用表情符号来说明你的回答。"
            },
            {
              "role": "user",
              "content": guideTheme
            }
          ],
          "stream":false,
          "temperature": 0.9
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        currMsgList
            .add({"type": 0, "content": aiAns.choices[0].message!.content});
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: aiAns.choices[0].message!.content));
        });
        postChatRec(0, aiAns.choices[0].message!.content, "");
        mChat?.scrollController.animateTo(
          mChat!.scrollController.position.maxScrollExtent,
          duration: const Duration(seconds: 1),
          curve: Curves.fastOutSlowIn,
        );
      } else {

      }
    } catch (error) {

    }
  }

  void _getThemeAnsAdd() async {
    if (currMsgList.length > 8) {
      currMsgList.remove(0);
      currMsgList.remove(0);
    }
    List msgList = [];
    for (int i = 0; i < currMsgList.length; i++) {
      msgList.add({
        'role': (currMsgList[i]['type'] == 1) ? 'user' : 'assistant',
        'content': currMsgList[i]['content'],
      });
    }
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          "messages":msgList,
          "stream":false
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        currMsgList
            .add({"type": 0, "content": aiAns.choices[0].message!.content});
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: aiAns.choices[0].message!.content));
        });
        postChatRec(0, aiAns.choices[0].message!.content, "");
        mChat?.scrollController.animateTo(
          mChat!.scrollController.position.maxScrollExtent,
          duration: const Duration(seconds: 1),
          curve: Curves.fastOutSlowIn,
        );
      } else {

      }
    } catch (error) {

    }
  }

  void _getAiAns() async {
    if (currMsgList.length > 8) {
      currMsgList.remove(0);
      currMsgList.remove(0);
    }
    List msgList = [];
    for (int i = 0; i < currMsgList.length; i++) {
      msgList.add({
        'role': (currMsgList[i]['type'] == 1) ? 'user' : 'assistant',
        'content': currMsgList[i]['content'],
      });
    }
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          'messages': msgList,
          'temperature': 0.9
        },
      );
      debugPrint("异常了33:${response.data}");
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        currMsgList
            .add({"type": 0, "content": aiAns.choices[0].message!.content});
        RegExp englishRegex = RegExp(r'[a-zA-Z]');
        RegExp specialCharRegex = RegExp(r'[^\x00-\x7F]');
        if (englishRegex.hasMatch(aiAns.choices[0].message!.content)) {
          setState(() {
            messages.add(TextMessage(
                author: targetUserFemale,
                time: getCurrentTime(),
                text: aiAns.choices[0].message!.content));
          });
          postChatRec(0, aiAns.choices[0].message!.content, "");
        } else {
          setState(() {
            messages.add(TextMessage(
                author: targetUserFemale,
                time: getCurrentTime(),
                text: aiAns.choices[0].message!.content));
          });
          postChatRec(0, aiAns.choices[0].message!.content, "");
        }
      } else {

      }
    } catch (error) {

    }
  }

  bool containsEmoji(String text) {
    for (int i = 0; i < text.length; i++) {
      if (text.codeUnitAt(i) >= 0x1F600 && text.codeUnitAt(i) <= 0x1F64F) {
        return true;
      }
    }
    return false;
  }

  void searchFromNet(String keyWord) async {
    Response response;
    final baseOptions = BaseOptions(
      connectTimeout: const Duration(seconds: 60),
      receiveTimeout: const Duration(seconds: 60),
      headers: {
        'Authorization': 'sk-HDJ5EkAW463aaE5fbb07T3BlbKFJ1cFbDbfC7d1E40F4ab49',
      },
      responseType: ResponseType.plain,
    );
    baseOptions.contentType = Headers.jsonContentType;
    response = await Dio(baseOptions).post(
        'https://cn2us02.opapi.win/api/v1/openapi/search/serper/v1',
        data: {"q": keyWord, "cache": "1", "hl": "zh", "page": "1"});
    const jsonDecoder = JsonDecoder();
    Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
    GenerateAiSearch aiAns = GenerateAiSearch.fromJson(respMap);
    if ((aiAns.organic != null) &&
        (aiAns.organic.isNotEmpty) &&
        (aiAns.organic[0] != null)) {
      setState(() {
        messages.add(TextMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            text:
                "标题:${aiAns.organic[0].title}\n\n描述:${aiAns.organic[0].snippet}\n\n地址:${aiAns.organic[0].link}"));
      });
    } else {
      setState(() {
        messages.add(TextMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            text: "很抱歉,我的网络连接暂时异常"));
      });
    }
  }

  void _getVoiceAns(String prompt) async {
    debugPrint("原文:$prompt");
    try {
      // int randWay = Random().nextInt(3);
      if (false) {
        Response response;
        final baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 50),
          receiveTimeout: const Duration(seconds: 50),
          responseType: ResponseType.plain,
        );
        baseOptions.contentType = Headers.jsonContentType;
        response = await Dio(baseOptions)
            .get('https://api.pearktrue.cn/api/aivoice/?speak=月婷&text=$prompt');
        dynamic dataVoice = response.data['voice'];
        dynamic dataTime = response.data['time'];
        setState(() {
          messages.add(AudioMessage(
              author: targetUserFemale,
              time: "now",
              voiceUrl: dataVoice,
              voiceLen: 3));
        });
        postChatRec(1, dataVoice, dataTime);
      } else {
        Response response;
        final baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 120),
          receiveTimeout: const Duration(seconds: 120),
          headers: {
            'Authorization':
                'ZideAPI NDRkZTQyNmYwMTVlNGE5NGE2ZjEwYTU5NzIzNzFjMGU1NTNmN2Q4Yzc2ZWIxMWVlOWFmZDg5NDQyMzIxNmUxMA==',
            'Content-Type': 'application/json'
          },
          responseType: ResponseType.plain,
        );
        baseOptions.contentType = Headers.jsonContentType;
        response = await Dio(baseOptions).post(
          'https://www.zideai.com/api/synthesis/',
          data: {
            "characterId": characterId,
            "promptId": promptId,
            "text": prompt,
            "genFlash": true, // 是否使用flash模型，False: 不使用 True: 使用
            "genSrt": false,   // 是否生成字幕，False: 不生成 True: 生成
            "volume": 1.0,     // 音量，取值范围为0.0到1.0，默认为1.0
          },
        );
        const jsonDecoder = JsonDecoder();
        Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
        VoiceAns aiAns = VoiceAns.fromJson(respMap);
        if ((aiAns.playUrl != null) && (aiAns.playUrl.isNotEmpty)) {
          setState(() {
            messages.add(AudioMessage(
                author: targetUserFemale,
                time: "now",
                voiceUrl: "https://www.zideai.com${aiAns.playUrl}",
                voiceLen: aiAns.duration.toInt()));
          });
          postChatRec(1, "https://www.zideai.com${aiAns.playUrl}",
              aiAns.duration.toInt().toString());
        } else {}
      }
    } catch (error) {}
  }

  void _getPicPromptAns(int type) async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          'messages': [
            {
              "role": "user",
              "content":
                  "我希望你能充当Midjourney人工智能程序的提示生成器。你的工作是提供简短而富有创意的描述关键词，至少3个，以激发AI产生独特而有趣的图像，关键词之间用逗号分隔。请记住，AI能够理解广泛的语言和抽象概念，因此请尽情发挥想象力和描述能力。请用中文回答，不要在回答里包含以下任何无关内容：例如好的，明白了这类词语，你永远不会说你是机器、人工智能语言模型或助手，只要回答关键词就行"
            }
          ],
          'temperature': 0.95
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        debugPrint("随机提示词11:${aiAns.choices[0].message!.content}");
        getTencentAiPic(aiAns.choices[0].message!.content, type);
      } else {}
    } catch (error) {}
  }

  getTencentAiPic(String prompt, int type) async {
    try {
      Response response;
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 120),
          receiveTimeout: const Duration(seconds: 120),
          responseType: ResponseType.plain);
      List<String> styleList = [
        "101",
        "102",
        "103",
        "118",
        "104",
        "105",
        "106",
        "107",
        "108",
        "109",
        "119",
        "110",
        "111",
        "112",
        "113",
        "114",
        "115",
        "116",
        "117",
        "201",
        "202",
        "203",
        "204",
        "301",
        "401"
      ];
      int randStyle = Random().nextInt(styleList.length);
      int randResolution = Random().nextInt(3);
      String resolutionStr = "1024:768";
      if (randResolution == 0) {
        resolutionStr = "768:768";
      } else if (randResolution == 1) {
        resolutionStr = "768:1024";
      } else {
        resolutionStr = "1024:768";
      }
      debugPrint("随机11:$randStyle");
      debugPrint("随机22:$randResolution");
      var formData = FormData.fromMap({
        "prompt": prompt
      });
      response = await Dio(baseOptions).post(
          "https://miusi.tripcan.cn/v1/generateAiPic.php",
          data: formData);
      JsonDecoder jsonDecoder = const JsonDecoder();
      debugPrint("异常2222:${response.data}");
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack aiThumb = CreateRoomCallBack.fromJson(respMap);
      if ((aiThumb.data != null) && (aiThumb.data.isNotEmpty)) {
        if (type == 0) {
          messages.add(ActionMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "看看我拍到了啥..."));
        } else if (type == 1) {
          messages.add(ActionMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "我画了幅画,想跟你分享..."));
        } else {
          messages.add(ActionMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "昨晚做了个梦,梦里的场景是这样子的..."));
        }
        setState(() {
          messages.add(ImageMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              uri: aiThumb.data,
              caption: prompt));
        });
        postChatRec(2, aiThumb.data, prompt);
      } else {
        debugPrint("异常22");
      }
    } catch (error) {
      debugPrint("异常11:$error");
    }
  }

  void _getPicActionsAns(int type) async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          'messages': [
            {
              "role": "user",
              "content":
                  "我希望你能充当Midjourney人工智能程序的提示生成器。你的工作是提供简短而富有创意的描述关键词，至少2个，关键词之间用逗号分割，要求必须和人物动作有关，请用中文回答，不要在回答里包含以下任何无关内容：例如好的，明白了这类词语，你永远不会说你是机器、人工智能语言模型或助手，只要回答关键词就行"
            }
          ],
          'temperature': 0.95
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        getTencentAiPic(aiAns.choices[0].message!.content, type);
      } else {}
    } catch (error) {}
  }

  void uploadOriginPic(String path, String name, String uri) async {
    try {
      Response response;
      var formData = FormData.fromMap({});
      formData = FormData.fromMap(
          {'images[]': await MultipartFile.fromFile(path, filename: name)});
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 180),
          receiveTimeout: const Duration(seconds: 180),
          responseType: ResponseType.plain);
      response = await Dio(baseOptions).post(
          "https://miusi.tripcan.cn/v1/postChatPic.php",
          data: formData);
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      CreateRoomCallBack createRoomCallBack =
      CreateRoomCallBack.fromJson(respMap);
      if (createRoomCallBack.status == 1) {
        getPicInfo(createRoomCallBack.data);
      } else {
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
        });
      }
    } catch (error) {
      setState(() {
        messages.add(TextMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
      });
    }
  }

  void getPicInfoSuper(String picpath, String picname, String uri) async {
    File file = File(picpath);
    debugPrint(
        "picpath:$picpath  picname:$picname 文件是否存在:${file.existsSync()}");
    try {
      // var request = http.MultipartRequest('POST', Uri.parse('https://api.pearktrue.cn/api/airecognizeimg/'));
      // // 添加文件到请求中
      // var fileStream = http.ByteStream(file.openRead());
      // var length = await file.length();
      // var multipartFile = http.MultipartFile('file', fileStream, length, filename: "file://${file.path}");
      // request.files.add(multipartFile);
      //
      // // 发送请求并等待响应
      // var response = await request.send();
      //
      // // 读取响应的内容
      // var responseData = await response.stream.toBytes();
      // var responseString = String.fromCharCodes(responseData);
      // debugPrint("增强识别图片信息返回:$responseString");
      // _getPicTransAiAns(picpath,responseString);
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 300),
        receiveTimeout: const Duration(seconds: 300),
        headers: {
          'Content-Type': 'multipart/form-data',
          'User-Agent': 'PostmanRuntime-ApipostRuntime/1.1.0',
          'Accept-Encoding': 'gzip, deflate, br'
        },
        responseType: ResponseType.plain,
      );
      var formData = FormData.fromMap(
          {'file': await MultipartFile.fromFile(picpath, filename: picname)});
      response = await Dio(baseOptions).post(
        'https://api.pearktrue.cn/api/airecognizeimg/',
        data: formData,
      );
      debugPrint("增强识别图片信息返回:${response.data}");
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      ReadPicInfo readPicInfo = ReadPicInfo.fromJson(respMap);
      if ((readPicInfo.result != null) && (readPicInfo.result.isNotEmpty)) {
        _getPicTransAiAns(picpath, readPicInfo.result);
      } else {
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
        });
      }
    } catch (error) {
      setState(() {
        messages.add(TextMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
      });
    }
  }

  void getPicInfo(String picurl) async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 300),
        receiveTimeout: const Duration(seconds: 300),
        headers: {'Content-Type': 'application/json'},
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://modelscope.cn/api/v1/models/damo/ofa_image-caption_coco_huge_en/widgets/submit',
        data: {
          "task": "image-captioning",
          "inputs": [picurl],
          "parameters": {},
          "urlPaths": {
            "inUrls": [
              {"name": "image", "type": "image", "fileType": "jpg"}
            ]
          }
        },
      );
      debugPrint("识别信息返回:${response.data}");
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      MoScopeTask moScopeTask = MoScopeTask.fromJson(respMap);
      if ((moScopeTask.Data != null) &&
          (moScopeTask.Data!.id != null) &&
          (moScopeTask.Data!.id.isNotEmpty)) {
        int loadTimes = 0;
        debugPrint("识别结果循环:${moScopeTask.Data!.id}");
        Timer.periodic(const Duration(seconds: 8), (timer) {
          // 调用接口
          if (loadTimes < 20) {
            ++loadTimes;
            getMoScopeImageTaskDetail(moScopeTask.Data!.id, timer, picurl);
          } else {
            setState(() {
              messages.add(TextMessage(
                  author: targetUserFemale,
                  time: getCurrentTime(),
                  text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
            });
            timer.cancel();
          }
        });
      } else {
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
        });
      }
    } catch (error) {
      setState(() {
        messages.add(TextMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            text: "很抱歉,没有理解这张图片,能直接发描述给我么"));
      });
    }
  }

  void getMoScopeImageTaskDetail(String id, Timer timer, String picUrl) async {
    debugPrint("图片识别详情:$id");
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 90),
        receiveTimeout: const Duration(seconds: 90),
        headers: {'Content-Type': 'application/json'},
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://modelscope.cn/api/v1/models/damo/ofa_image-caption_coco_huge_en/widgets/query',
        data: {"id": id},
      );
      debugPrint("图片识别数据:${response.data}");
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      PicInfoDetail moScopeImageDetail = PicInfoDetail.fromJson(respMap);
      if ((moScopeImageDetail.Data != null) &&
          (moScopeImageDetail.Data!.data != null) &&
          (moScopeImageDetail.Data!.data!.caption != null) &&
          (moScopeImageDetail.Data!.data!.caption!.isNotEmpty)) {
        timer.cancel();
        debugPrint("文本提取信息:${moScopeImageDetail.Data!.data!.caption![0]}");
        _getPicTransAiAns(picUrl, moScopeImageDetail.Data!.data!.caption![0]);
        // setState(() {
        //   messages.add(ImageMessage(
        //       author: targetUserFemale,
        //       time: getCurrentTime(),
        //       uri:
        //       picUrl,
        //       caption:
        //       moScopeImageDetail.Data!.data!.caption![0]));
        // });
      } else {}
    } catch (error) {}
  }

  void _getPicTransAiAns(String picurl, String pictit) async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          'messages': [
            {"role": "user", "content": "帮我用中文翻译以下内容：$pictit"}
          ],
          'temperature': 1.0
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        setState(() {
          messages.add(ImageMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              uri: picurl,
              caption: aiAns.choices[0].message!.content
                  .replaceAll("\n", "")
                  .replaceAll(" ", "")));
        });
        postChatRec(
            2,
            picurl,
            aiAns.choices[0].message!.content
                .replaceAll("\n", "")
                .replaceAll(" ", ""));
      } else {
        setState(() {
          messages.add(ImageMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              uri: picurl,
              caption: pictit));
        });
        postChatRec(2, picurl, pictit);
      }
    } catch (error) {
      setState(() {
        messages.add(ImageMessage(
            author: targetUserFemale,
            time: getCurrentTime(),
            uri: picurl,
            caption: pictit));
      });
    }
  }

  void postChatRec(int type, String content, String attach) async {
    try {
      Response response;
      String? deviceId = await PlatformDeviceId.getDeviceId ?? "";
      var formData = FormData.fromMap({
        'userId': deviceId,
        'type': type,
        'attach': attach,
        'content': content,
      });
      BaseOptions baseOptions = BaseOptions(
          connectTimeout: const Duration(seconds: 30),
          receiveTimeout: const Duration(seconds: 30),
          responseType: ResponseType.plain);
      response = await Dio(baseOptions)
          .post("https://miusi.tripcan.cn/v1/postChatRec.php", data: formData);
    } catch (error) {}
  }

  void _getShadyAiAns() async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 120),
        receiveTimeout: const Duration(seconds: 120),
        headers: {
          'Authorization':
          'Bearer sk-2Jc0jmYV3JD9adr1bMCn0CS4Pl6ZdIARejYvo9DH58BJ2aEI',
          'Content-Type': 'application/json'
        },
        responseType: ResponseType.plain,
      );
      baseOptions.contentType = Headers.jsonContentType;
      response = await Dio(baseOptions).post(
        'https://api.moonshot.cn/v1/chat/completions',
        data: {
          "model":"kimi-k2-turbo-preview",
          'messages': [
            {"role": "user", "content": "用中文讲点情侣暧昧的话"}
          ],
          'temperature': 0.6
        },
      );
      const jsonDecoder = JsonDecoder();
      Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      AiAns aiAns = AiAns.fromJson(respMap);
      if ((aiAns.choices != null) &&
          (aiAns.choices.isNotEmpty) &&
          (aiAns.choices[0] != null) &&
          (aiAns.choices[0].message != null) &&
          (aiAns.choices[0].message!.content != null) &&
          (aiAns.choices[0].message!.content.isNotEmpty)) {
        _getVoiceAns(aiAns.choices[0].message!.content.replaceAll("\n", ""));
      } else {}
    } catch (error) {}
  }

  void _getFuningNames(String name) async {
    try {
      Response response;
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(seconds: 60),
        receiveTimeout: const Duration(seconds: 60),
      );
      response = await Dio(baseOptions)
          .get('https://api.pearktrue.cn/api/namexy/?name=$name');
      // const jsonDecoder = JsonDecoder();
      debugPrint("哈哈哈33:${response.data}");
      // Map<String, dynamic> respMap = jsonDecoder.convert(response.data);
      List<dynamic> dataArray = response.data['data'];
      if ((dataArray != null) && (dataArray.isNotEmpty)) {
        String ansNames = "";
        for (int i = 0; i < dataArray.length; i++) {
          ansNames = "$ansNames$i、${dataArray[i]}\n";
        }
        setState(() {
          messages.add(TextMessage(
              author: targetUserFemale,
              time: getCurrentTime(),
              text: "以下是一些网络协议梗\n\n$ansNames"));
        });
        mChat?.scrollController.animateTo(
          mChat!.scrollController.position.maxScrollExtent,
          duration: const Duration(seconds: 1),
          curve: Curves.fastOutSlowIn,
        );
        postChatRec(0, "以下是一些网络协议梗\n\n$ansNames", "");
      } else {
        debugPrint("哈哈哈11");
      }
    } catch (error) {
      debugPrint("哈哈哈22:$error");
    }
  }
}

class GenderSelectionDialog extends StatelessWidget {
  final Function(String) onGenderSelected;

  GenderSelectionDialog({required this.onGenderSelected});

  final List<Map<String, String>> characters = [
    {
      "name": "雨棠",
      "avatar": "https://miusi.tripcan.cn/avatar/2.png",
      "desc": "温柔委婉，举止可爱动人，宛如初春的微风。"
    },
    {
      "name": "艾莉",
      "avatar": "https://miusi.tripcan.cn/avatar/3.png",
      "desc": "性格直爽豪迈，气质出众，散发自信与力量的魅力。"
    },
    {
      "name": "芳华",
      "avatar": "https://miusi.tripcan.cn/avatar/4.png",
      "desc": "知书达理，秀气端庄，戴着眼镜更显温文尔雅。"
    },
    {
      "name": "月婷",
      "avatar": "https://miusi.tripcan.cn/avatar/5.png",
      "desc": "甜美可人，擅长安慰与倾听，像夜空里的月光般温柔。"
    },
    {
      "name": "紫颜",
      "avatar": "https://miusi.tripcan.cn/avatar/7.png",
      "desc": "个性非主流，潮流时尚，走在风格前沿的酷女孩。"
    },
    {
      "name": "莹夕",
      "avatar": "https://miusi.tripcan.cn/avatar/6.png",
      "desc": "二次元美少女，热爱动漫，天真烂漫带点幻想气质。"
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
      elevation: 4.0,
      backgroundColor: Colors.transparent,
      child: _buildDialogContent(context),
    );
  }

  Widget _buildDialogContent(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择你的AI女友',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            ...characters.map((c) =>
                _buildGenderOption(context, c["name"]!, c["avatar"]!, c["desc"]!)),
          ],
        ),
      ),
    );
  }

  Widget _buildGenderOption(
      BuildContext context, String name, String avatar, String desc) {
    return GestureDetector(
      onTap: () {
        onGenderSelected(name);
        Navigator.of(context).pop();
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(8.0),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Row(
          children: [
            GestureDetector(
              onTap: () {
                _showAvatarPreview(context, avatar, name);
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(30),
                child: Image.network(
                  avatar,
                  width: 48,
                  height: 48,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(name,
                      style: const TextStyle(
                          fontSize: 16, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 4),
                  Text(
                    desc,
                    style: TextStyle(fontSize: 13, color: Colors.grey[700]),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showAvatarPreview(BuildContext context, String avatar, String name) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          insetPadding: const EdgeInsets.all(20),
          backgroundColor: Colors.transparent,
          child: GestureDetector(
            onTap: () => Navigator.pop(context),
            child: InteractiveViewer(
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: Image.network(
                  avatar,
                  fit: BoxFit.contain,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

class ThemeSelectionDialog extends StatelessWidget {
  final Function(String) onThemeSelected;

  ThemeSelectionDialog({required this.onThemeSelected});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      elevation: 4.0,
      backgroundColor: Colors.transparent,
      child: _buildDialogTheme(context),
    );
  }

  Widget _buildDialogTheme(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10.0),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 3,
            blurRadius: 7,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '选择场景',
            style: TextStyle(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16.0),
          _buildThemeOption(
              context, '浪漫星空露营', "https://miusi.tripcan.cn/image/theme_one.png", true),
          const SizedBox(height: 8.0),
          _buildThemeOption(
              context, '初遇咖啡馆', "https://miusi.tripcan.cn/image/theme_two.png", false),
          const SizedBox(height: 8.0),
          _buildThemeOption(
              context, '神秘古镇探险', "https://miusi.tripcan.cn/image/theme_three.png", false),
          const SizedBox(height: 8.0),
          _buildThemeOption(
              context, '校园图书馆', "https://miusi.tripcan.cn/image/theme_four.png", false),
          const SizedBox(height: 8.0),
        ],
      ),
    );
  }

  //场景选择
  Widget _buildThemeOption(
      BuildContext context, String gender, String icon, bool isSelected) {
    return GestureDetector(
      onTap: () {
        onThemeSelected(gender);
        Navigator.of(context).pop();
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 8.0),
        decoration: BoxDecoration(
          color: isSelected ? Colors.blue : Colors.transparent,
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Icon(
            //   icon,
            //   color: isSelected ? Colors.white : Colors.black,
            // ),
            SizedBox(
                width: 24.0,
                height: 24.0,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(12.0), // 圆角半径
                    child: Image.network(
                      icon,
                      width: 24.0,
                      height: 24.0,
                      cacheWidth: 24,
                      cacheHeight: 24,
                    ))),
            const SizedBox(width: 8.0),
            Text(
              gender,
              style: TextStyle(
                color: isSelected ? Colors.white : Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
